package com.qf.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author H
 * @create 2020-10-15 0:03
 * @Description:
 */
@RestController
public class UserController {
    @RequestMapping("/login")
    public String login(@RequestBody Map map) {
        String loginName = (String) map.get("loginName");


        String password = (String) map.get("password");

        System.out.println("获取到的账号密码" + loginName + "======" + password);

        Subject subject = SecurityUtils.getSubject();
        System.out.println("subject+++++++" + subject);
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(loginName, password);
            System.out.println("令牌token++++" + token);


            subject.login(token);
        } catch (UnknownAccountException ex) {
            System.out.println("账户不存在" + ex.getMessage());
        } catch (IncorrectCredentialsException e) {
            System.out.println("密码不正确" + e.getMessage());
        } catch (Exception exx) {
            System.out.println(exx.getMessage());
        }
        if (subject.isAuthenticated()) {
            return "success";
        } else {
            return "fail";
        }
    }

    @RequestMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "success";
    }
}
